
Date.prototype.format = function (fmt) {
	let o = {
		"M+": this.getMonth() + 1,                 //月份
		"d+": this.getDate(),                    //日
		"h+": this.getHours(),                   //小时
		"m+": this.getMinutes(),                 //分
		"s+": this.getSeconds(),                 //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds()             //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (let k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}

const initCalendar = (year, month) => {
	//注: js中的月份是从0开始的,
	//获取当月的第一天是星期几
	let firstDate = new Date(year, month - 1).getDay();
	//获取当月的最后一天是几号
	let lastDate = new Date(year, month, 0).getDate();
	//做日期头的转换, getDay()方法默认星期天为0
	firstDate = firstDate - 1 < 0 ? 6 : firstDate - 1
	// firstDate = firstDate
	let dateArr = [];
	//添加前一个月剩下的日期
	// let befYear = year, befMonth = month - 1
	// if(befMonth == 0) {
	// 	befYear = year - 1
	// 	befMonth = 12
	// }
	for (let i = 0; i < firstDate; i++) {
		let timeStamp = new Date(year, month - 1, 1).getTime() - 86400000 * (firstDate - i);
		let day = new Date(timeStamp).getDate();
		dateArr.push({
			inMonth: false,
			day,
			isSelect: false,
			weekDay: weekNameFilter(new Date(timeStamp).getDay()),
			date: new Date(timeStamp).format('yyyy-MM-dd'),
			isCurrentDay: false
		})
	}
	let nowDate = new Date().format('yyyy-MM-dd')
	//添加当月剩下的日期
	for (let i = 1; i < lastDate + 1; i++) {
		let day = new Date(year, month - 1, i).getDate();
		dateArr.push({
			inMonth: true,
			day,
			isSelect: false,
			weekDay: weekNameFilter(new Date(year, month - 1, i).getDay()),
			date: new Date(year, month - 1, i).format('yyyy-MM-dd'),
			isCurrentDay: nowDate == new Date(year, month - 1, i).format('yyyy-MM-dd') ? true : false
		})
	}
	//添加下月日期
	// let dateCount = 42 //日历总共有多少天
	// let d_len = dateArr.length // 已经添加日期的数组长度
	let lastDay = new Date(year, month, 0).getDay()
	lastDay = lastDay == 0 ? 7 : lastDay
	lastDay = 7 - lastDay
	for (let i = 0; i < lastDay; i++) {
		let timeStamp = new Date(year, month, 1).getTime() + 86400000 * i;
		let day = new Date(timeStamp).getDate();
		dateArr.push({
			inMonth: false,
			day,
			isSelect: false,
			weekDay: weekNameFilter(new Date(year, month, i + 1).getDay()),
			date: new Date(year, month, i + 1).format('yyyy-MM-dd'),
			isCurrentDay: false
		})
	}
	return dateArr
}

const weekNameFilter = (val) => {
	let weekNameArr = ['日', '一', '二', '三', '四', '五', '六']
	return `星期${weekNameArr[val]}`
}

export default initCalendar;